package cn.graydove.bot.utils;

import cn.graydove.bot.adapter.GroupMessageEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.mamoe.mirai.message.data.Message;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.function.Function;

public final class CommonUtils {

    public static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static <T>boolean in(T element, Iterable<T> container) {
        if (container == null)
            return false;
        for (T i: container) {
            if (Objects.equals(i, element))
                return true;
        }
        return false;
    }

    public static <R, T>boolean in(R element, Iterable<T> container, Function<T, R> function) {
        if (container == null)
            return false;
        for (T i: container) {
            R r = function.apply(i);
            if (Objects.equals(r, element))
                return true;
        }
        return false;
    }

    public static String getName(GroupMessageEvent event) {
        String name = event.getSender().getNameCard();
        if (StringUtils.isEmpty(name)) {
            name = event.getSender().getNick();
        }
        return name;
    }

    public static MessageChainBuilder append(Message message) {
        return new MessageChainBuilder().append(message);
    }

}
